package com.jswdwsx.esign.service

import com.jswdwsx.esign.commom.ResEnum
import com.jswdwsx.esign.entity.FlowTemplatePO
import com.jswdwsx.esign.entity.RequestPO
import com.jswdwsx.esign.protocol.EsignApi
import com.jswdwsx.esign.protocol.request.CreateFileByTemplateReq
import com.jswdwsx.esign.repo.FileTemplateRepository
import org.slf4j.LoggerFactory.getLogger
import org.springframework.stereotype.Service


@Service
class FileService(
    private val esignApi: EsignApi,
    private val fileTemplateRepository: FileTemplateRepository
) {

    private val logger = getLogger(FileService::class.java)

    /**
     * 根据模板创建文件，涉及模板参数填充
     */
    fun createFileByTemplate(requestPO: RequestPO, templatePO: FlowTemplatePO): Map<String, String> {
        // 查询流程模板对应的文件
        val fileTemplates = fileTemplateRepository.findAllByFlowTemplateId(templatePO.id!!)
        val fileMap = HashMap<String, String>()
        fileTemplates.forEach {
            val req = CreateFileByTemplateReq(
                it.fileTemplateId,
                it.name,
                requestPO.fileFillParam
            )
            fileMap[it.fileTemplateId] = createFile(req)
        }
        return fileMap
    }

    fun createFile(createFileByTemplateReq: CreateFileByTemplateReq): String {
        logger.info("创建文件请求参数,createFileByTemplateReq:${createFileByTemplateReq}")

        val esignResp = esignApi.createFileByTemplate(fileReq = createFileByTemplateReq)
        return esignResp.data(ResEnum.CallEsignFlowCreateFail).fileId
    }
}
